package progress.exa29_2.part2.noUi;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class NoUIServer {

    private static int clientNo = 0;

    public static void main(String[] args) {
                /*
        建立一个线程创建服务器实例并启动监听
         */
        new Thread(()->{
            try{
                //创建服务器套接字，服务器端口号设为8000
                ServerSocket serverSocket = new ServerSocket(8000);
                System.out.println(("Server started at"+new Date()+'\n'));

                //进入无线循环
                while(true){

                    //服务器进入监听状态
                    Socket socket = serverSocket.accept();
                    //有客户端连接服务端，客户数加一
                    clientNo++;
                    System.out.println("客户端连接数: "+clientNo+"  "+new Date()+'\n');

                    InetAddress inetAddress = socket.getInetAddress();
                    System.out.println("客户端 "+clientNo+" 号 的主机名为： "+inetAddress.getHostName()+'\n');
                    System.out.println("客户端 "+clientNo+"号的IP地址为： "+inetAddress.getHostAddress()+'\n');

                    //为客户端创建新线程进行持续交互
                    new Thread(new HandleAClient(socket)).start();

                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }).start();
    }

}

/**
 * 持续交互任务定义
 */
class HandleAClient implements Runnable{

    //此任务的客户端套接字
    private Socket socket;

    public HandleAClient(Socket socket) {
        this.socket=socket;
    }

    public void run() {
        try{
            //创建服务器接受和发送数据的流
            DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());
            DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

            //持续监听客户端发送的数据
            while(true) {
                double radius = inputFromClient.readDouble();
                double area=radius*radius*Math.PI;
                outputToClient.writeDouble(area);
                System.out.println("得到客户端的半径数据： "+radius+'\n');
                System.out.println("计算出来的面积为: "+area+'\n');
            }
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
